package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion.......");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle......");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        log.info("请求url:{}",url);
        if(url.contains("login")){
            log.info("is login, release");
            return true;
        }
        String jwt = request.getHeader("token");
        if(StringUtils.isEmpty(jwt)){
            log.info("token is empty");
            Result error = Result.error("NOT_LOGIN");
            String jsonError = JSONObject.toJSONString(error);
            response.getWriter().write(jsonError);
            return false;
        }
        try{
            Claims claims = JwtUtils.parseJWT(jwt);

        }catch (Exception e){
            e.printStackTrace();
            log.info("令牌错误");
            Result error = Result.error("NOT_LOGIN");
            String jsonError = JSONObject.toJSONString(error);
            response.getWriter().write(jsonError);
            return false;
        }
        log.info("令牌合法，放行");
        return true;
    }
}
